package com.zxp;


import com.zxp.utils.configParseUtils.JsonAppender;
import com.zxp.utils.configParseUtils.JsonConfigReader;
import com.zxp.utils.fileUtils.*;
import com.zxp.utils.logUtils.ErrorLogger;
import com.zxp.utils.winEnvUtils.EnvUtils;
import org.apache.commons.cli.*;

import java.util.List;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    /**
     * The main entry point of the application.
     *
     * @param args The command-line arguments.
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("Hello World!");
////        控制控制台不退出
//        System.out.println("Press Enter to exit...");
//        Scanner scanner = new Scanner(System.in);
//        scanner.nextLine();
        // Create a command line parser
        CommandLineParser parser = new DefaultParser();
        // Create a Options object
        Options options = new Options();
        //jdkm init
        options.addOption("init", false, "Initialize config file");
        //List available JDKs
        options.addOption("als", false, "List current JDK installations.");
        //Install a JDK
        options.addOption("install", true, "Install available remote JDK");
        //Switch to use a JDK
        options.addOption("use", false, "Switch to use the specified version.");
        //Remove a JDK
        options.addOption("remove", false, "Remove a specific version.");
        //List installed JDKs
        options.addOption("ls", false, "Show a list of versions available for download.");
        options.addOption("proxy", false, "Set a proxy to use for downloads.");
        // Parse the command line arguments
        try {
            CommandLine cmd = parser.parse(options, args);
//            System.out.println("Command line arguments: " + cmd.getArgList());
//            System.out.println("Option -init: " + cmd.hasOption("init"));
//            System.out.println("Option -list: " + cmd.hasOption("list"));
            // 处理不同的命令
            if (cmd.hasOption("init")) {
                // 处理 init 命令
                System.out.println("Handling init command...");
                handleInitCommand(cmd);
            } else if (cmd.hasOption("als")) {
                // 处理 list 命令
                handleListCommand(cmd);
            }else if (cmd.hasOption("install")) {
                // 处理 list 命令
                System.out.println("Handling install command...");
                String jdkVersion = cmd.getOptionValue("install");
                System.out.println("Installing JDK version: " + jdkVersion);
                handleInstallCommand(cmd);
            }else if (cmd.hasOption("use")) {
                //handle use command
                System.out.println("Handling use command...");
                String jdkVersion = cmd.getOptionValue("use");
                System.out.println("Switching to use JDK version: " + jdkVersion);
            }else if (cmd.hasOption("remove")) {
                //handle remove command
                System.out.println("Handling remove command...");
                String jdkVersion = cmd.getOptionValue("remove");
                System.out.println("Removing JDK version: " + jdkVersion);
            }else if (cmd.hasOption("ls")) {
                //handle ls command
                System.out.println("Handling ls command...");
                List<String> strings = DirectoryListReader.listDirectories("jdks");
                for (String string : strings) {
                    System.out.println(string);
                }
            }
        } catch (ParseException e) {
            System.err.println("Command line parsing failed. Error: " + e.getMessage());
            ErrorLogger.logError("Command line parsing failed. Error: " + e.getMessage());
        }
    }

    /**
     * Handles the logic for the init command.
     * Creates the initial directory structure and sets up the environment variables.
     *
     * @param cmd The CommandLine object representing the parsed command-line arguments.
     */
    private static void handleInitCommand(CommandLine cmd) {
        try{
            //Print JAVA_HOME environment variables
            String javaHome = EnvUtils.querySystemEnvironmentVariable("JAVA_HOME");
            if (javaHome != null) {
                System.out.println("Now JAVA_HOME at: " + javaHome);
            }
            //Print current directory
            String currentDirectory = DirectoryListReader.getCurrentDirectory();
            System.out.println("Current install directory: " + currentDirectory);
            //New system environment variables: key:jdkm_home value:currentDirectory
            EnvUtils.modifyOrAddSystemEnvironmentVariable("JDKM_HOME", currentDirectory);
            //Append current directory to system path
            EnvUtils.appendToSystemPath(currentDirectory);
//            EnvUtils.appendToSystemPath(currentDirectory);
//            EnvUtils.modifyOrAddSystemEnvironmentVariable("Jdkh", currentDirectory );
            //Create init folder
            FolderCreator.createFolder(currentDirectory + "/repository/jdks");
            FolderCreator.createFolder(currentDirectory + "/logs");
            FolderCreator.createFolder(currentDirectory + "/config");
            FileUtils.createFile(currentDirectory + "/config/jdkm.json");
            //Save init config file
            JsonAppender.setJsonFile(currentDirectory + "/config/jdkm.json");
            JsonAppender.appendKeyValuePair("Init_JAVA_HOME", javaHome);
        }catch (IOException | InterruptedException e){
            ErrorLogger.logError("Error occurred: " + e.getMessage());
            //Print error message
            System.out.println("Error occurred，please check error_log.txt in jdkm/logs directory.");
        }
    }

    /**
     * Handles the logic for the list/als command.
     * Retrieves and prints all JDK keys under the "jdk" key using JsonConfigReader.
     *
     * @param cmd The CommandLine object representing the parsed command-line arguments.
     */
    private static void handleListCommand(CommandLine cmd) {
        // Process the logic for the list/als command
        System.out.println("Handling list/als command...");

        // Retrieve all keys under the "jdk" key using JsonConfigReader
        List<String> jdks = JsonConfigReader.getAllKeysUnderKey("jdk");

        // Print the list of JDKs
        for (String jdk : jdks) {
            System.out.println(jdk);
        }
    }
    /**
     * Handles the logic for the install command.
     * Downloads the specified JDK version and unzips it to the repository/jdks directory.
     *
     * @param cmd The CommandLine object representing the parsed command-line arguments.
     * @throws IOException If an I/O error occurs during the download or unzip process.
     */
    private static void handleInstallCommand(CommandLine cmd) throws IOException {
        // 处理 install 命令的逻辑
        System.out.println("Handling install command...");
        String jdkVersion = cmd.getOptionValue("install");
        System.out.println("Installing JDK version: " + jdkVersion);
        String jdkUrl = JsonConfigReader.getString("jdk." + jdkVersion);
//        String currentDirectory = DirectoryListReader.getCurrentDirectory();
//        FileDownloader.downloadFileWithBar(jdkUrl, currentDirectory + "/repository/jdks/" + jdkVersion + ".zip");
//        FileUnzipper.unzip(currentDirectory + "/repository/jdks/" + jdkVersion + ".zip", currentDirectory + "/repository/jdks/" + jdkVersion);
//        FileDeleter.deleteFile(currentDirectory + "/repository/jdks/" + jdkVersion + ".zip");
//        System.out.println("JDK version " + jdkVersion + " installed successfully.");
        int downloadThreads = 4;
        ExecutorService executorService = Executors.newFixedThreadPool(downloadThreads);
        executorService.submit(() -> {
            try {
                String currentDirectory = DirectoryListReader.getCurrentDirectory();
                try {
                    FileDownloader.downloadFileWithBar(jdkUrl, currentDirectory + "/repository/jdks/" + jdkVersion + ".zip");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                executorService.shutdown(); // 关闭下载线程池
            }
        });
        try {
            executorService.awaitTermination(Long.MAX_VALUE, java.util.concurrent.TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //installed successfully and unzip
        String currentDirectory = DirectoryListReader.getCurrentDirectory();
        FileUnzipper.unzip(currentDirectory + "/repository/jdks/" + jdkVersion + ".zip",
                currentDirectory + "/repository/jdks/" + jdkVersion);
        FileDeleter.deleteFile(currentDirectory + "/repository/jdks/" + jdkVersion + ".zip");
        System.out.println("JDK version " + jdkVersion + " installed successfully.");
    }
    /**
     * Prints the help message.
     *
     * @param options The Options object representing the command-line options.
     */
    private static void printHelp(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar YourExecutable.jar", options);
    }
}